# app.py
from flask import Flask, request, jsonify, render_template, session
import requests
import json
import time
from datetime import timedelta

app = Flask(__name__)
app.secret_key = 'your_secret_key_here'  # 用于session加密
app.permanent_session_lifetime = timedelta(hours=2)  # session保持2小时

# 百度文心API配置
API_KEY = "Un8cSWZ8GJhcEumWTGvQfoHn"
SECRET_KEY = "vAOuWKMCufAOjGY7Hpj8Sh9zOIW6DFrc"
API_URL = "https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat/completions_pro"

def get_access_token():
    """
    获取百度API access token
    """
    url = f"https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={API_KEY}&client_secret={SECRET_KEY}"
    response = requests.get(url)
    print("Access Token Response:", response.text)  # 调试信息
    if response.status_code == 200:
        return response.json().get("access_token")
    return None

@app.route('/')
def home():
    # 初始化会话历史
    if 'messages' not in session:
        session['messages'] = []
    return render_template('index.html', messages=session['messages'])

@app.route('/chat', methods=['POST'])
def chat():
    try:
        user_message = request.json.get('message')
        print(f"收到用户消息: {user_message}")  # 调试信息
        
        # 获取或初始化会话历史
        if 'messages' not in session:
            session['messages'] = []
        
        # 将用户消息添加到历史记录
        session['messages'].append({"role": "user", "content": user_message})
        
        # 获取access token
        access_token = get_access_token()
        if not access_token:
            print("获取access token失败")  # 调试信息
            return jsonify({'response': '获取访问令牌失败'}), 500

        # 准备请求URL和头部
        url = f"{API_URL}?access_token={access_token}"
        headers = {
            'Content-Type': 'application/json'
        }
        
        # 准备请求体，包含历史消息
        # 限制历史消息数量，防止超过API限制
        messages_to_send = session['messages'][-10:]  # 只发送最近10条消息
        
        payload = {
            "messages": messages_to_send,
            "temperature": 0.7,
            "stream": False
        }
        
        print(f"发送到API的请求: {json.dumps(payload, ensure_ascii=False)}")  # 调试信息
        
        # 发送请求到百度API
        response = requests.post(url, headers=headers, json=payload)
        print(f"API响应状态码: {response.status_code}")  # 调试信息
        print(f"API响应内容: {response.text}")  # 调试信息
        
        if response.status_code == 200:
            result = response.json()
            bot_response = result.get('result', '')
            if not bot_response:
                bot_response = result.get('response', result.get('content', '抱歉，我没有获取到有效回复'))
            
            # 将AI回复添加到历史记录
            session['messages'].append({"role": "assistant", "content": bot_response})
            session.modified = True  # 确保session更新被保存
            
            return jsonify({
                'response': bot_response,
                'history': session['messages']  # 返回完整的对话历史
            })
        else:
            error_msg = f"API调用失败: {response.status_code} - {response.text}"
            print(error_msg)  # 调试信息
            return jsonify({'response': '抱歉，服务器出现问题'}), 500

    except Exception as e:
        print(f"发生错误: {str(e)}")  # 调试信息
        return jsonify({'response': f'服务器错误: {str(e)}'}), 500

@app.route('/clear_history', methods=['POST'])
def clear_history():
    """清除对话历史"""
    session['messages'] = []
    return jsonify({'status': 'success'})

if __name__ == '__main__':
    app.run(debug=True)